package logic

import (
	"context"
	"fmt"
	"fresh/freshrpc/freshrpc"
	"fresh/freshrpc/internal/svc"
	"fresh/modesl/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line

	tx := mysql.DB.Debug().Begin()
	
	var class mysql.Class
	err := tx.Where("name=?", in.ClassName).Find(&class).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("查询分类失败")
	}
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err = tx.Create(&class).Error
		if err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("添加分类失败")
		}
	}

	var brand mysql.Brand
	err = tx.Where("name=?", in.BrandName).Find(&brand).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("查询品牌失败")
	}

	if brand.ID == 0 {
		brand = mysql.Brand{
			Name: in.BrandName,
		}
		err = tx.Create(&brand).Error
		if err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("添加品牌失败")
		}

	}
	good := mysql.Goods{
		Title:   in.Title,
		Image:   in.Image,
		Price:   float64(in.Price),
		ClassId: int64(class.ID),
		BrandId: int64(brand.ID),
	}

	err = tx.Create(&good).Error
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("添加商品失败")
	}

	tx.Commit()
	return &freshrpc.FreshAddResponse{
		GoodsId: int64(good.ID),
	}, nil
}
